package myJs

import myJs.Implicits._
import myJs.myPkg._
import myJs.myPkg.jquery._
import myJs.tool.Tool
import org.scalajs.dom.ext.Ajax
import org.scalajs.dom.{Element, document}
import scalatags.Text.all._
import shared.VarTool

import scala.collection.immutable.SeqMap
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
import scala.scalajs.js
import scala.scalajs.js.Dynamic.{global => g}
import scala.scalajs.js.JSON
import scala.scalajs.js.annotation.{JSExport, JSExportTopLevel}

/**
 * Created by yz on 6/5/2021
 */
@JSExportTopLevel("CellDetailInfo")
object CellDetailInfo {

  val profileId = "profile"
  val formId = "form"
  val comparisonId = "comparison"
  val kind = VarTool.cellKind

  @JSExport("init")
  def init = {
    initText
    initShow
    refreshTable
    $(":input.myToggle").bootstrapToggle()
    bootstrapValidator
    registerEvent
    DetailInfo.refreshDataset.map { x =>
      initTab
      //      refreshProfileImage
    }

  }

  def initTab = {
    getTab match {
      case VarTool.profileTabId =>
        Tool.selectTab(profileId)
        refreshProfileImage
      case _ =>
    }
  }

  def initShow = {
    val log2Show = kind match {
      case VarTool.pathwayKind | VarTool.cellKind => false
      case _ => true
    }
    if (!log2Show) $(".myLog2").hide()
  }

  def initText = {
    val data = Tool.getTextData(kind)
    $("#showName").text(data.showName)
  }

  def registerEvent = {
    $(document.body).on("click", s"#${profileId} .myRun", "", (y: Element) => {
      refreshProfileImage
    })
    $(document.body).on("click", ".mySelectAll", "", (y: Element) => {
      selectAll(y)
    })
    $(document.body).on("click", s"#${comparisonId} .myRun", "", (y: Element) => {
      refreshComparisonImage
    })
  }

  def selectAll(y: Element) = {
    val select2Jq = $(y).parents(".form-group").find("select")
    select2Jq.find(">option").prop("selected", true)
    select2Jq.trigger("change")
  }

  def refreshProfileImage = {
    Tool.useLoadingF() { () =>
      refreshProfileImageF
    }
  }

  def refreshComparisonImage = {
    Tool.useLoadingF() { () =>
      refreshComparisonImageF
    }
  }

  def toggle2TF(formJq: JQuery) = {
    formJq.find(s".myToggle").foreach { y =>
      if (!$(y).isChecked) {
        val html = input(`type` := "hidden", name := $(y).nameAttr, value := s"FALSE")
        $(y).after(html.render)
      }
    }
  }

  def refreshProfileImageF = {
    val tabId = profileId
    val formJq = $(s"#profile #form")
    val bv = formJq.bv
    bv.validate()
    val valid = bv.isValid()
    if (valid) {
      val url = g.jsRoutes.controllers.CellController.getProfileImage().url.toString
      toggle2TF(formJq)
      val formData = formJq.serialize()
      Ajax.post(url = s"${url}", data = formData, headers = Map("Content-Type" -> "application/x-www-form-urlencoded")).map { xhr =>
        val rs = xhr.responseText.toJDJAn
        val valid = rs("valid").toB
        if (valid) {
          val absImageJq = $(s"#${tabId} #abs img")
          absImageJq.attr("src", s"data:image/png;base64,${rs("absBase64")}")
          absImageJq.attr(Tool.dataBasicType, s"pdf")
          absImageJq.parents(".myCharts").findInputByName("pdfBase64").
            `val`(rs("absPdfBase64").toString)
          val relImageJq = $(s"#${tabId} #rel img")
          relImageJq.attr("src", s"data:image/png;base64,${rs("relBase64")}")
          relImageJq.attr(Tool.dataBasicType, s"pdf")
          relImageJq.parents(".myCharts").findInputByName("pdfBase64").
            `val`(rs("relPdfBase64").toString)
          $(s"#${profileId} #result").show()
        } else {
          $(s"#${profileId} #result").hide()
          Swal.swal(SwalOptions.title("Error").text(rs("message")).`type`("error"))
        }
      }
    } else Future {}
  }

  def refreshComparisonImageF = {
    val tabId = comparisonId
    val formJq = $(s"#${tabId} #form")
    val url = g.jsRoutes.controllers.CellController.getComparisonImage().url.toString

    toggle2TF(formJq)
    val formData = formJq.serialize()
    Ajax.post(url = s"${url}", data = formData,
      headers = Map("Content-Type" -> "application/x-www-form-urlencoded")).map { xhr =>
      val rs = xhr.responseText.toJDJAn
      val valid = rs("valid").toB
      if (valid) {
        val absImageJq = $(s"#${tabId} #abs img")
        absImageJq.attr("src", s"data:image/png;base64,${rs("absBase64")}")
        absImageJq.attr(Tool.dataBasicType, s"pdf")
        absImageJq.parents(".myCharts").findInputByName("pdfBase64").
          `val`(rs("absPdfBase64").toString)
        val relImageJq = $(s"#${tabId} #rel img")
        relImageJq.attr("src", s"data:image/png;base64,${rs("relBase64")}")
        relImageJq.attr(Tool.dataBasicType, s"pdf")
        relImageJq.parents(".myCharts").findInputByName("pdfBase64").
          `val`(rs("relPdfBase64").toString)
        $(s"#${tabId} #result").show()
      } else {
        $(s"#${tabId} #result").hide()
        Swal.swal(SwalOptions.title("Error").text(rs("message")).`type`("error"))
      }
    }
  }

  def getTab = {
    g.tab.toString
  }

  def getIdStr = {
    g.id.toString
  }

  def refreshTable = {
    val tableMap = VarTool.cellMap
    val url = g.jsRoutes.controllers.CellController.getDetail().url.toString
    Ajax.get(url = s"${url}?id=${getIdStr}").map { xhr =>
      val data = xhr.responseText.toJDJAn.toMyJDS
      val html = tableMap.map { case (fieldName, header) =>
        val v = data(fieldName)
        val finalV = fieldName match {
          case "geneCards" =>
            a(href := s"${v}", target := "_blank",
              v)
          case "pathwayName" =>
            a(href := s"${data("msigdbLink")}", target := "_blank", v)
          case _ => span(v)
        }
        tr(
          th(header),
          td(finalV)
        )
      }.mkString("&nbsp;")
      $("#table tbody").html(html)
    }
  }

  def bootstrapValidator = {
    val maxNumber = Double.MaxValue
    val dict = js.Dictionary(
      "feedbackIcons" -> js.Dictionary(
        "valid" -> "glyphicon glyphicon-ok",
        "invalid" -> "glyphicon glyphicon-remove",
        "validating" -> "glyphicon glyphicon-refresh",
      ),
      "fields" -> {
        js.Dictionary(
          "kinds[]" -> js.Dictionary(
            "validators" -> js.Dictionary(
              "choice" -> js.Dictionary(
                "message" -> "Dataset selection is required！",
                "min" -> 1
              ),
            )
          ),
        )
      }
    )
    g.$(s"#${profileId} #${formId}").bootstrapValidator(dict)
  }


}
